﻿using BLL.Interface;
using Common.Extensions;
using DAL.Interface;
using Microsoft.EntityFrameworkCore;
using Model;
using Model.DTO.Member;
using Model.DTO.Public.GetList;
using Model.DTO.Public.OperateId;
using Model.Entity.Member;
using Model.Entity.Type;
using Model.Entity.User;

namespace BLL
{
    /// <summary>
    /// 会员业务逻辑层
    /// </summary>
    public class MemberBLL : IMemberBLL
    {
        private readonly IBaseDAL_LONG<TB_Member> _memberDAL;
        private readonly IBaseDAL<TB_MemberType> _memberTypeDAL;
        private readonly IBaseDAL<TB_User> _userDAL;
        public MemberBLL(
            IBaseDAL_LONG<TB_Member> memberDAL,
            IBaseDAL<TB_MemberType> memberTypeDAL,
            IBaseDAL<TB_User> userDAL
            )
        {
            _memberDAL = memberDAL;
            _memberTypeDAL = memberTypeDAL;
            _userDAL = userDAL;
        }
        /// <summary>
        /// 添加会员
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ResponseMessage> AddMember(AddMemberDTO param)
        {
            try
            {
                var member = await _memberDAL.GetEntityAllAsync(x => x.UserId == param.UserId && x.MemberTypeId == param.MemberTypeId).Result.FirstOrDefaultAsync();
                bool result;
                if (member != null)
                {
                    member.ExpiredTime = member.ExpiredTime.AddDays(param.Day ?? 0).AddHours(param.Hour ?? 0).AddMinutes(param.Minute ?? 0);
                    result = await _memberDAL.EditEntityAsync(member);
                }
                else
                {
                    var level = 1;
                    var experienceCap = level * (level + 1) / 2;
                    member = new TB_Member()
                    {
                        Level = level,
                        ExperienceCap = experienceCap * 100,
                        ExpiredTime = DateTime.Now.AddDays(param.Day ?? 0).AddHours(param.Hour ?? 0).AddMinutes(param.Minute ?? 0)
                    };
                    param.CopyPropertiesTo(member);
                    result = await _memberDAL.AddEntityAsync(member);
                }
                return result ? ResponseMessage.CreateSuccess("添加成功") : ResponseMessage.CreateError("添加失败");
            }
            catch
            {
                return ResponseMessage.CreateError("添加失败");
            }
        }
        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ResponseMessage> DeleteMember(OperateIdDTO_LONG param)
        {
            try
            {
                if (param.Id > 0)
                {
                    param.Ids.Clear();
                    param.Ids.Add(param.Id);
                    param.Id = 0;
                    return await DeleteMember(param);
                }
                #region 过滤
                if (param.Ids.Count <= 0)
                {
                    return ResponseMessage.CreateError("Id无效");
                }
                #endregion
                using var tran = await _memberDAL.BeginTransactionAsync();
                try
                {
                    foreach (var id in param.Ids)
                    {
                        await _memberDAL.DeleteEntityAsync(id);
                    }
                    await tran.CommitAsync();
                    return ResponseMessage.CreateSuccess("删除成功");
                }
                catch
                {
                    await tran.RollbackAsync();
                    throw;
                }
            }
            catch
            {
                return ResponseMessage.CreateError("删除失败");
            }
        }
        /// <summary>
        /// 编辑会员
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ResponseMessage> EditMember(EditMemberDTO param)
        {
            try
            {
                #region 过滤
                var member = await _memberDAL.GetEntityAllAsync(x => x.Id == param.Id).Result.FirstOrDefaultAsync();
                if (member == null)
                {
                    return ResponseMessage.CreateError("会员不存在");
                }
                var existMemberType = await _memberTypeDAL.GetEntityAllAsync(x => x.Id == param.MemberTypeId).Result.AnyAsync();
                if (!existMemberType)
                {
                    return ResponseMessage.CreateError("会员类型不存在");
                }
                #endregion
                param.CopyPropertiesTo(member);
                var result = await _memberDAL.EditEntityAsync(member);
                return result ? ResponseMessage.CreateSuccess("修改成功") : ResponseMessage.CreateError("修改失败");
            }
            catch
            {
                return ResponseMessage.CreateError("修改失败");
            }
        }
        /// <summary>
        /// 获取会员列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ResponseMessage> GetMemberList(GetListDTO param)
        {
            try
            {
                #region 参数校验
                if (param.Page <= 0)
                {
                    param.Page = 1;
                }
                if (param.Size <= 0)
                {
                    param.Size = 10;
                }
                #endregion
                var users = await _userDAL.GetEntityAllAsync(x => x.UserName.Contains(param.Query ?? ""));
                var userIds = await users.Select(x => x.Id).ToListAsync();
                var members = await _memberDAL.GetEntityAllAsync(x => userIds.Contains(x.UserId));
                var total = await members.CountAsync();
                var returnMemberLists = from user in users
                                        join member in members on user.Id equals member.UserId
                                        select new ReturnMemberListDTO
                                        {
                                            UserName = user.UserName,
                                            UserId = user.Id,
                                            MemberTypeId = member.MemberTypeId,
                                            Level = member.Level,
                                            Experience = member.Experience,
                                            ExperienceCap = member.ExperienceCap,
                                            ExpiredTime = member.ExpiredTime
                                        };
                var list = returnMemberLists.ToListAsync();
                return ResponseMessage.CreateSuccess("获取成功", new { total, list });
            }
            catch
            {
                return ResponseMessage.CreateError("获取失败");
            }
        }
    }
}
